package com.itheima.tliasmanager.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tliasmanager.exception.ClassNotAllowedDeleteExceptio;
import com.itheima.tliasmanager.mapper.ClazzMapper;
import com.itheima.tliasmanager.mapper.StudentMapper;
import com.itheima.tliasmanager.pojo.Dto.QueryParam;
import com.itheima.tliasmanager.pojo.Vo.PageResult;
import com.itheima.tliasmanager.pojo.domain.Clazz;
import com.itheima.tliasmanager.pojo.domain.Student;
import com.itheima.tliasmanager.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }

    @Override
    public List<Clazz> listAllClazz() {
        List<Clazz> clazzList = clazzMapper.listAllClazz();

        return clazzList;
    }

    @Override
    public PageResult<Clazz> page(QueryParam queryParam) {
        log.info("分页查询班级列表，参数：{}",queryParam);
        PageHelper.startPage(queryParam.getPage(),queryParam.getPageSize());
        Page<Clazz> page = (Page<Clazz>)clazzMapper.queryPageList(queryParam);

        page.getResult().stream().forEach(clazz -> clazz.panDuan());

        PageResult<Clazz> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getResult());
        log.info("分页查询结果：{}",pageResult);
        return pageResult;
    }

    @Override
    public void removeById(Integer id) {
        log.info("删除班级信息，参数：{}",id);
        List<Student> studentList = studentMapper.listByClazzId(id);
        if (studentList!=null && !studentList.isEmpty()){
            throw new ClassNotAllowedDeleteExceptio("该班级有学生，不允许删除");
        }
        clazzMapper.removeById(id);
    }

    @Override
    public Clazz getById(Integer id) {
        log.info("查询班级信息，参数：{}",id);
        Clazz clazz = clazzMapper.findById(id);
        return clazz;
    }

    @Override
    public void updateClazz(Clazz clazz) {
        log.info("修改班级信息，参数：{}",clazz);
        clazzMapper.updateClazz(clazz);
    }
}
